package com.slipper.system.interceptor;

import com.slipper.PaasContext;
import com.slipper.common.exception.NotLoginException;
import com.slipper.common.permit.PermitService;
import com.slipper.common.util.Tool;
import com.slipper.system.common.Constants;
import com.slipper.system.common.UserDetail;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录验证过滤器
 */
public class AuthInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) throws Exception {
        // 屏蔽所有get请求
        String relativePath = Tool.getRelativePath(request);
        if("".equals(relativePath) || "/".equals(relativePath)) {
            request.getRequestDispatcher("/static/index.html").forward(request, response);
            return false;
        }

        try {
            UserDetail userDetail = Constants.getCurrentUser();
            if (userDetail.isSuperAdmin()) {
                return true; // 超管不做权限限制
            }

            if (!PaasContext.getBean(PermitService.class).hasPermit(relativePath)
                    && !userDetail.hasPermit(relativePath)) { // 无权限
                request.getRequestDispatcher("/error/forbidden").forward(request, response);
                return false;
            }
        } catch (NotLoginException e) {
            request.getRequestDispatcher("/error/notLogin").forward(request, response);
            return false;
        }
        return true;
    }
}
